package model

import (
	"fmt"
	"goadmin/conf"
	"goadmin/utils"

	"gorm.io/gorm"
)

type User struct {
	BaseModel
	Username string `gorm:"type:varchar(20);not null;uniqueIndex:udx_default" json:"username"`
	Password string `gorm:"type:varchar(150);not null" json:"-"`
	Nickname string `gorm:"type:varchar(20);not null;default:''" json:"nickname"`
	Avatar   string `gorm:"type:varchar(250);not null;default:''" json:"avatar"`
	Auth     uint   `gorm:"type:smallint;not null;default:0" json:"auth"`
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
	if u.Nickname == "" {
		u.Nickname = u.Username
	}
	if u.Password != "" {
		if hash, err := utils.GeneratePwdHash(u.Password); err != nil {
			return err
		} else {
			u.Password = hash
		}
	}
	return nil
}

func (u *User) BeforeDelete(tx *gorm.DB) (err error) {
	if u.Username == conf.User.Super {
		return fmt.Errorf("super user can't be deleted")
	}
	return nil
}
